﻿using System;
using System.Linq;

namespace Borg.Framework
{
    public abstract class FrameworkStartup
    {
        public virtual void Init()
        {
            Runtime.Repository.PluginAdded += PluginAdded;
            Runtime.Repository.PluginRemoved += PluginRemoved;

            foreach (var pi in Runtime.Repository.PluginInfos)
                Register(pi);
        }

        private void PluginAdded(object sender, PluginEventArgs args)
        {
            Register(args.PluginInfo);
        }

        private void PluginRemoved(object sender, PluginEventArgs args)
        {
            Unregister(args.PluginInfo);
        }

        protected abstract void Register(PluginInfo pi);
        protected abstract void Unregister(PluginInfo pi);
    }

    public abstract class FrameworkStartup<T> : FrameworkStartup
        where T : Attribute
    {
        public abstract void ExtensionCreated(object s, ExtensionEventArgs args);
        public abstract void ExtensionReleased(object s, ExtensionEventArgs args);

        public abstract void Register(ExtensionTypeInfo extType);

        protected override void Register(PluginInfo pi)
        {
            foreach (var eti in pi.ExtensionTypeInfos.
                Where(eti => AssemblyAnalyzer.GetCustomAttributes<T>(eti.Type).Count > 0))
            {
                eti.ExtensionCreated += ExtensionCreated;
                eti.ExtensionReleased += ExtensionReleased;
                    
                Register(eti);
            }
        }

        public abstract void Unregister(ExtensionTypeInfo extType);
        
        protected override void Unregister(PluginInfo pi)
        {
            foreach (var eti in pi.ExtensionTypeInfos)
            {
                eti.ExtensionCreated -= ExtensionCreated;
                Unregister(eti);
            }
        }
    }
}

